package com.shopping.controller;

import com.shopping.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@RestController
@RequestMapping("/api/adminhome")
public class FileUploadController {

    // 设置上传目录，存储在 uploads/images/ProductImage 目录
    private static final String UPLOAD_DIR = "F:/网络应用开发/实验/main/java-shopping-web/uploads/images/ProductImage/"; // 绝对路径

    // 上传文件的接口
    @PostMapping("/image")
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("上传的文件为空！");
        }

        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            log.info("上传文件，文件名为：{}", fileName);

            // 设置上传路径（将文件保存在 static/images/ProductImage 目录中）
            Path path = Paths.get(UPLOAD_DIR + fileName);

            // 创建上传目录（如果不存在）
            Files.createDirectories(path.getParent());

            // 将文件保存到指定路径
            file.transferTo(path);

            // 返回上传成功的响应
            return Result.success("http://localhost/api/images/ProductImage/"+fileName);
        } catch (IOException e) {
            return Result.error("上传失败");
        }
    }
}
